#include "MagicSquares.h"

int size;


int main(){
    
    int** magicbox;
    int i,j;

    printf("\nMagic Squares by Conrad Stack\n\n");

    if((size = getSize()) == -1){
        printf("Error: this is not an odd number\n");
        return EXIT_FAILURE;
    }
       
    magicbox = produceTable();
    
    if((saveTable(magicbox,size)) == 0)
        return EXIT_FAILURE;
    
    for(i=0;i<size;i++){
        for (j=0;j<size;j++) {
            free(&magicbox[i][j]);
        }
    }

    return EXIT_SUCCESS;

}

int getSize(){
    int size;
    printf("Please input an odd number to be the size of your table: ");
    scanf("%d",&size);
    if(size%2 == 0 | size < 0)
        return -1;
    return size;
    
}

int** produceTable(){
    int** temparray;
    int i,j,maxnum,curr_row,curr_col,max_row,max_col;
    int temprow,tempcol;
    maxnum = size * size;
    max_row = size -1;
    max_col = size -1;
    /* initialize a new multidimensional array */
    temparray = calloc(size, sizeof(int *));
    if(temparray == NULL){
        printf("out of memory\n");
        exit(1);
    }
    for(i=0;i<size;i++){
        temparray[i] = calloc(size,sizeof(int));
        if(temparray[i] == NULL){
            printf("out of memory\n");
            exit(1);
        }
    }

    /* initialize all positions to 0 */
    for(i=0;i<size;i++){
        for(j=0;j<size;j++){
            temparray[i][j] = 0;
        }
    }

   /* start algorithm */
    curr_row = max_row;
    curr_col = max_col/2;
    temparray[curr_row][curr_col] = 1;
    for(i=2;i<maxnum+1;i++){
        temprow = curr_row;
        tempcol = curr_col;
        if(curr_row == max_row)
            temprow = 0;
        else
            temprow++;
        if(curr_col == max_col)
            tempcol = 0;
        else
            tempcol++;
        if(temparray[temprow][tempcol] == 0){
            temparray[temprow][tempcol] = i;
            curr_row = temprow;
            curr_col = tempcol;
        }
        else{
            if(curr_row == 0){
                curr_row = max_row;
                curr_col++;
                temparray[curr_row][curr_col] = i;
            }
            else{
                curr_row--;
                temparray[curr_row][curr_col] = i;
            }
        }
            
    }
    return temparray;

}

int saveTable(int** table, int size){
    char filename[10];
    char asize[10];
    FILE* outfile;
    int i,j;

    sprintf(asize,"%d",size);   
    strcpy(filename,"magic-");
    strcat(filename,asize);
    strcat(filename,".txt");
    if((outfile = fopen(filename,"w")) == NULL){
        printf("Error: unable to write to file %s\n",filename);
        return 0;
    }    
    for(i=0;i<size;i++){
        for (j=0;j<size;j++) {
            fprintf(outfile,"%d ",table[i][j]);
        }
        fprintf(outfile,"\n");
    }
    printf("\noutput to: %s\n\n",filename);
    return 1;

}


